package com.luffyzhao.demo.utils;

import java.util.*;

import org.apache.commons.lang3.time.*;
import org.apache.commons.io.*;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.*;

public class FileUtil {
    /**
     * 移动目录
     *
     * @param file
     * @param targetDirPath
     * @throws IOException
     */
    public static void moveToTargetDir(final File file, final String targetDirPath) throws IOException {
        final File targetDir = new File(targetDirPath);
        final String currentDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        final File targetDateDir = new File(targetDir, currentDate);
        final File targetFile = new File(targetDateDir, file.getName());
        if (targetFile.exists()) {
            FileUtils.forceDelete(targetFile);
        }
        if (file.exists()) {
            FileUtils.moveFileToDirectory(file, targetDateDir, true);
        }
    }

    /**
     * 写入目录
     *
     * @param data
     * @param fileName
     * @param targetDirPath
     * @throws IOException
     */
    public static void writeToTargetDir(final String data, final String fileName, final String targetDirPath) throws IOException {
        final File targetDir = new File(targetDirPath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        final File msgFile = new File(targetDir, fileName);
        FileUtils.write(msgFile, (CharSequence) data, StandardCharsets.UTF_8);
    }

    /**
     * 写入目录带日期
     *
     * @param data
     * @param fileName
     * @param targetDirPath
     * @throws IOException
     */
    public static void writeToTargetDirToDate(final String data, final String fileName, final String targetDirPath) throws IOException {
        final File targetDir = new File(targetDirPath);
        final String currentDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        final File targetDateDir = new File(targetDir, currentDate);
        final File msgFile = new File(targetDateDir, fileName);
        FileUtils.write(msgFile, (CharSequence) data, StandardCharsets.UTF_8);
    }


    /**
     * 目录下的文件
     * @param targetDirPath
     * @return
     */
    public static Collection<File> getFileList(final String targetDirPath) {
        if (StringUtils.isEmpty((CharSequence) targetDirPath)) {
            throw new IllegalArgumentException("\u62a5\u6587\u53d1\u9001\u76ee\u5f55\u6ca1\u6709\u914d\u7f6e,\u8bf7\u5148\u914d\u7f6e");
        }
        final File dir = new File(targetDirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return (Collection<File>) FileUtils.listFiles(dir, (String[]) null, true);
    }
}
